package com.jxy.bean.attribute;

import com.jxy.bean.ClassFile;
import com.jxy.bean.constant.ConstantPoolTag;
import com.jxy.bean.constant.Utf8Info;
import com.jxy.tool.Tool;

import java.io.DataInputStream;

public class Attribute {
    private int attribute_name_index;
    private ClassFile cf;
    private AttributeInfo info;

    public Attribute(DataInputStream dis, ClassFile cf) {
        this.cf = cf;
        attribute_name_index = Tool.readU2(dis);
        if (getAttributeName().equals("Code")) {
            info = new AttributeCodeInfo(dis, cf);
        } else if (getAttributeName().equals("SourceFile")) {
            info = new AttributeSourcefileInfo(dis, cf);
        } else if (getAttributeName().equals("BootstrapMethods")) {
            info = new AttributeBootstrapMethodInfo(dis, cf);
        } else if (getAttributeName().equals("LineNumberTable")) {
            info = new AttributeLineNumberInfo(dis, cf);
        } else {
            info = new AttributeDefaultInfo(dis, cf);
            //TODO 暂时只解析这么多
            //System.out.println("----------------" + getAttributeName() + "----------------");
        }
    }

    public AttributeInfo getInfo() {
        return info;
    }

    //暂时只校验名字索引
    public boolean valid() {
        //attribute_name_index必须指向CONSTANT_Utf8_info结构
        if (cf.getPools()[attribute_name_index].getTag() == ConstantPoolTag.CONSTANT_Utf8.getTag()) {
            return true;
        }
        return false;
    }

    //获取属性名，也就是属性类型
    public String getAttributeName() {
        if (valid()) {
            Utf8Info utf8Info = (Utf8Info) cf.getPools()[attribute_name_index];
            return utf8Info.getString();
        }
        return "attribute_name_index err !";
    }

    @Override
    public String toString() {
        return "Attribute{" +
                "attribute_name_index=" + attribute_name_index + "(" + getAttributeName() +
                "), info=" + info +
                '}';
    }
}
